//
//  WNCommentVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/14.
//

import UIKit

class WNCommentVC: WNBaseVC {
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    lazy var blackBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.backgroundColor = .init(white: 1, alpha: 0.01)
        btn.rx.tap.bind { [weak self] in
            if self?.keyboardStatus == 1 {
                self?.hidKeyboard()
            }
        }.disposed(by: rx.disposeBag)
        return btn
    }()
    
    lazy var sendView: CommentSendView = {
        return CommentSendView()
    }()
    
    lazy var comTabView: WNTableView = {
        let tab = WNTableView.init(frame: CGRect.zero, style: .plain)
        tab.delegate = self
        tab.dataSource = self
        tab.register(CommentCell.self, forCellReuseIdentifier: CommentCell.identifier)
        tab.ly_emptyView = WNEmptyView.wn_loadStyle(descStr: .comment, imageStr: .comment, tapBlock: { [weak self] in
            tab.mj_header?.beginRefreshing()
        })
        tab.isHidden = true
        return tab
    }()
    
    /// 键盘状态 0: 收起 1: 弹出
    var keyboardStatus: Int = 0
        
    var sendViewBottom: CGFloat = 0

    var sendViewHeight: CGFloat = SendHeight+TabBarMargin
    
    var commnetArr = [CommentDetailModel]() 
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        hidKeyboard()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        handleNoti()
    }
    
    override func viewConfig() {
        view.addSubview(blackBtn)
        view.addSubview(comTabView)
        view.addSubview(sendView)
        blackBtn.snp.makeConstraints { (make) in
            make.top.equalTo(NaviTotalHeight)
            make.left.right.equalTo(0)
            make.bottom.equalTo(-sendViewHeight)
        }
        comTabView.snp.makeConstraints { (make) in
            make.top.equalTo(NaviTotalHeight)
            make.left.right.equalTo(0)
            make.bottom.equalTo(-sendViewHeight)
        }
        sendView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(0)
            make.height.equalTo(sendViewHeight)
        }
        sendView.wn_cornerWithBorder(0, 0, .white, 1, .init(white: 0, alpha: 0.1), .init(width: 0, height: 1), 5)
        sendView.layer.masksToBounds = false
    }
    
    override func dataConfig() {
        pageName = "Commnet"
        listSettingRefresh()
        commentListRequest()
        sendView.sendClosure = { [weak self] str in
            self?.addComment(str)
        }
        sendView.heightClosure = { [weak self] height in
            self?.sendViewHeight = height
            self?.updateLayout(0, false)
        }
    }
    
    override func handleNoti() {
        NotificationCenter.default.addObserver(self, selector: #selector(showKeyboard(noti:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(hidKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    func listSettingRefresh() {
        comTabView.mj_header = wn_refreshHeader(completion: { [weak self] in
            self?.page = 1
            self?.hasPage = false
            self?.commentListRequest()
        })
        
        comTabView.mj_footer = wn_refreshFooter(completion: { [weak self] in
            if self?.page == 1 && (self?.commnetArr.count ?? 0) == 0 {
                self?.comTabView.mj_footer?.endRefreshing()
                return
            }
            if self?.hasPage == true {
                self?.page += 1
                self?.commentListRequest()
            }else {
                self?.comTabView.mj_footer?.endRefreshingWithNoMoreData()
            }
        })
    }
    
    // 键盘弹起状态 弹出
    @objc func showKeyboard(noti: Notification) {
        let info = noti.userInfo
        let dura = info![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
        let value = info![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue
        let frame = value.cgRectValue
        sendViewBottom = frame.size.height-TabBarMargin
        updateLayout(dura, false)
    }
    
    func updateLayout(_ dura: Double = 0.25, _ isH: Bool = true) {
        UIView.animate(withDuration: dura) {
            self.sendView.snp.updateConstraints { (make) in
                make.height.equalTo(self.sendViewHeight)
                make.bottom.equalTo(-self.sendViewBottom)
            }
            self.blackBtn.snp.updateConstraints { (make) in
                make.bottom.equalTo(-self.sendViewHeight-self.sendViewBottom)
            }
            self.keyboardStatus = isH ? 0 : 1
            if isH {
                self.view.sendSubviewToBack(self.blackBtn)
            }else {
                self.view.bringSubviewToFront(self.blackBtn)
            }
            self.view.layoutIfNeeded()
        }
    }
}

extension WNCommentVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        commnetArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CommentCell.identifier, for: indexPath) as! CommentCell
        cell.model = commnetArr[indexPath.item]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return commnetArr[indexPath.item].conHeight
    }
}

extension WNCommentVC {
    
    func commentListRequest() {
        provider_comment.rx.request(.getCommentList(baseId, page))
            .asObservable()
            .mapModel(BaseModel<CommentListModel>.self)
            .subscribe(onNext: { [weak self] (model) in
                self?.comTabView.isHidden = false
                self?.comTabView.ly_emptyView.imageStr = EmptyImage.comment.rawValue
                self?.comTabView.ly_emptyView.detailStr = EmptyDesc.comment.rawValue
                self?.comTabView.ly_emptyView.btnTitleStr = ""
                guard model.code == 0 else {
                    if (self?.isFirst ?? true) {
                        self?.comTabView.ly_emptyView.imageStr = EmptyImage.serverBad.rawValue
                        self?.comTabView.ly_emptyView.detailStr = EmptyDesc.serverBad.rawValue
                        self?.comTabView.ly_emptyView.btnTitleStr = "Click Refresh"
                    }else {
                        self?.wn_toast(model.msg ?? "")
                    }
                    self?.comTabView.mj_header?.endRefreshing()
                    self?.comTabView.mj_footer?.endRefreshing()
                    self?.isFirst = false
                    return
                }
                if self?.page == 1 {
                    self?.commnetArr.removeAll()
                    self?.comTabView.mj_footer?.resetNoMoreData()
                }
                self?.navView.titleName = "\(model.data?.total ?? 0)".wn_wan() + " Comments"
                if let arr = model.data?.list {
                    self?.hasPage = arr.count > 9
                    self?.commnetArr += arr
                }else {
                    self?.comTabView.mj_footer?.endRefreshingWithNoMoreData()
                }
                self?.comTabView.reloadData()
                self?.comTabView.mj_header?.endRefreshing()
                self?.comTabView.mj_footer?.endRefreshing()
                self?.isFirst = false
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
                self?.comTabView.ly_emptyView.imageStr = EmptyImage.netWork.rawValue
                self?.comTabView.ly_emptyView.detailStr = EmptyDesc.netWork.rawValue
                self?.comTabView.ly_emptyView.btnTitleStr = "Click Refresh"
                self?.comTabView.mj_header?.endRefreshing()
                self?.comTabView.mj_footer?.endRefreshing()
                self?.comTabView.isHidden = false
            }).disposed(by: rx.disposeBag)
    }
    
    func addComment(_ content: String) {
        WNHUD.wn_showLoading()
        provider_comment.rx.request(.addComment(baseId, content))
            .asObservable()
            .mapModel(BaseModel<CommentDetailModel>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    self?.hidKeyboard()
                    return
                }
                self?.wn_toast("Comment success")
                if let m = model.data {
                    self?.commnetArr.insert(m, at: 0)
                    self?.commnetArr[0].didFinishMapping()
                    self?.comTabView.scrollsToTop = true
                    self?.comTabView.reloadData()
                    self?.comTabView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
                }
                self?.hidKeyboard(true)
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
            }).disposed(by: rx.disposeBag)
    }
    
    @objc func hidKeyboard(_ isSend: Bool = false) {
        let str: String = isSend ? "" : sendView.textView.text
        showSendViewStr(str)
    }
    
    func showSendViewStr(_ str: String) {
        sendView.textView.text = str
        sendView.currentText = str
        sendView.textView.resignFirstResponder()
        sendView.textView.layoutSubviews()
        sendViewBottom = 0
        if isBlank(str) {
            sendView.textView.placeholder = "Write your comment here..."
            sendViewHeight = SendHeight+TabBarMargin
        }else {
            sendView.textViewDidChange(sendView.textView)
        }
        updateLayout()
        view.endEditing(true)
    }
}
